local root = Root:getInstance()
local MathAbs = math.abs
local PI = math.pi
--============================================================
local DeviceInfo = {}
DeviceInfo.Width = 720
DeviceInfo.Height = 1280
--============================================================
--==========用物体名称获取物体的Handler
local function getObjHandler(objName, sceneName)
	sceneName = sceneName or "scene1"
	if type(objName) == "string" and type(sceneName) == "string" then
		return Root:getInstance():getSceneManager(sceneName):getSceneNode(objName)
	end
	return nil
end
--============================================================
local NextAngle = Radian:new(0.0)
local FrameListener = false
local TouchEventListener = true
local FingerCount = 0
local MinDeltaFingerProgress = 0.001
----------------------------------------------------------
local FirstFinger = {}
FirstFinger.DirectionCtrl = {x=1, y=1}       -- if to rotate camera, please set it as -1
FirstFinger.DownPosition = {x=nil,y=nil}
FirstFinger.UpPosition = {x=nil,y=nil}
FirstFinger.DownTime = nil
FirstFinger.UpTime = nil
FirstFinger.UpDuration = {mini=10,maxi=5000}    --手指与屏幕接触的时间间隔控制
FirstFinger.MaxUpSpeed = {x=50,y=30}
FirstFinger.MovePosition = {x=nil,y=nil}
FirstFinger.PreMovePosition = {x=nil,y=nil}
FirstFinger.Sensitivity = {x=1.0,y=1.0}
FirstFinger.DeltaProgress = {x=0,y=0}
FirstFinger.DampingSpeed = {x=0.9,y=0.0}
FirstFinger.IsMoving = false
----------------------------------------------------------
local ObjectEvent = {}
ObjectEvent.ObjHandler = nil
ObjectEvent.IsMoving = false
ObjectEvent.ActiveFrame = false
ObjectEvent.SwitchEnable = {move=false,rotate=true,scale=true}
ObjectEvent.FromAngle = {x=0,y=0,z=0}
ObjectEvent.ToAngle = {x=0,y=2*PI,z=0}
ObjectEvent.AngleRange = {
	x=(ObjectEvent.ToAngle.x - ObjectEvent.FromAngle.x),
	y=(ObjectEvent.ToAngle.y - ObjectEvent.FromAngle.y),
	z=(ObjectEvent.ToAngle.z - ObjectEvent.FromAngle.z)
}
ObjectEvent.RotateAxis = 'y'
ObjectEvent.DirectionCtrl = {w=1, e=1, r=1}
ObjectEvent.Sensitivity = {w=1, e=1, r=1}
ObjectEvent.Progress = 0.0

function postCreateScene()
    local groupScene = getObjHandler("group1")
    ObjectEvent.ObjHandler = groupScene
    
    --帧监听
    function onFrameStarted(evt)
        if FrameListener then
            if ObjectEvent.ActiveFrame then
                if ObjectEvent.SwitchEnable.rotate then
                    print("in frame...-------------object progress:",ObjectEvent.Progress)
                    print("in frame...-------------delta progress:",FirstFinger.DeltaProgress.x)
                    ObjectEvent.Progress = ObjectEvent.Progress + FirstFinger.DeltaProgress.x
                    local progress = limiteProgress(ObjectEvent.Progress)
                    objRotateWithFinger(ObjectEvent, progress)
                    FirstFinger.DeltaProgress.x = FirstFinger.DeltaProgress.x * FirstFinger.DampingSpeed.x
                    print("in frame...-------------damping delta progress:",FirstFinger.DeltaProgress.x)
                    if MathAbs(FirstFinger.DeltaProgress.x) < MinDeltaFingerProgress then
                        print("<<<<<<<<<<<<<<<<go out>>>>>>>>>>>>>>>>>>")
                        ObjectEvent.ActiveFrame = false
                    end
                    print("*****************************")
                end
            end
        end
    end
    root:registerOnFrameStartHandler(onFrameStarted)
end

--============================================================
--物体跟随手指旋转
function objRotateWithFinger(objEvent, progress)
    --计算物体的Progress和下一个角度
    progress = objEvent.DirectionCtrl.e * objEvent.Sensitivity.e * progress
    local nextAngle = objEvent.FromAngle[objEvent.RotateAxis] + progress * objEvent.AngleRange[objEvent.RotateAxis]
    --转换成Radian类型，旋转物体
    NextAngle:setValueInRadians(nextAngle)
    objEvent.ObjHandler:getTransform():resetOrientation()
    if objEvent.RotateAxis == 'x' then
        objEvent.ObjHandler:getTransform():pitch(NextAngle)
    elseif objEvent.RotateAxis == 'y' then
        objEvent.ObjHandler:getTransform():yaw(NextAngle)
    elseif objEvent.RotateAxis == 'z' then
        objEvent.ObjHandler:getTransform():roll(NextAngle)
    end
    objEvent.Progress = progress
end

function limiteProgress(progress)
    return progress - math.floor(progress)
end

function onTouchEvent(action, id, x, y)
    if TouchEventListener then
        if id == 0 then
            --手指的down
            if action == 0 then
                FirstFinger.DownPosition.x = x
                FirstFinger.DownPosition.y = y
                FirstFinger.DownTime = root:getTimer():getMilliseconds()
                FingerCount = 1
                FrameListener = false
                FirstFinger.MovePosition.x = nil
                FirstFinger.MovePosition.y = nil
            --手指的move
            elseif action == 2 then
                FirstFinger.PreMovePosition.x = FirstFinger.MovePosition.x or x
                FirstFinger.PreMovePosition.y = FirstFinger.MovePosition.y or y
                FirstFinger.MovePosition.x = x
                FirstFinger.MovePosition.y = y
                --计算手指的progress的变化值
                local dx = FirstFinger.MovePosition.x - FirstFinger.PreMovePosition.x
                local dy = FirstFinger.MovePosition.y - FirstFinger.PreMovePosition.y
                FirstFinger.DeltaProgress.x = dx / DeviceInfo.Width
                FirstFinger.DeltaProgress.y = dy / DeviceInfo.Height
                
                FirstFinger.IsMoving = true
            --手指的up
            elseif action == 1 or action == 6 then
                FirstFinger.UpTime = root:getTimer():getMilliseconds()
                FirstFinger.UpPosition.x = x
                FirstFinger.UpPosition.y = y
                local tmpTime = FirstFinger.UpTime - FirstFinger.DownTime
                if tmpTime <= 0 then
                    tmpTime = FirstFinger.UpDuration.mini
                elseif tmpTime > FirstFinger.UpDuration.maxi then
                    tmpTime = FirstFinger.UpDuration.maxi
                end
                local xDistance = FirstFinger.UpPosition.x - FirstFinger.DownPosition.x
                FirstFinger.IsMoving = false
                
                if action == 1 then
                    FingerCount = 0
                    --手指的x变化速度控制物体ObjectEvent
                    FirstFinger.DeltaProgress.x = xDistance/tmpTime/FirstFinger.MaxUpSpeed.x
                    print("time:",tmpTime,"distance:",xDistance,"progress:",FirstFinger.DeltaProgress.x)
                    ObjectEvent.ActiveFrame = true
                    print("==================================")
                    FrameListener = true
                elseif action == 6 then
                    FingerCount = 1
                end
            end
        end
        
        if FingerCount == 1 then
            if FirstFinger.IsMoving then
                --用手指的x的progress变化控制ObjectEvent
                if ObjectEvent.SwitchEnable.rotate then
                    local firstFingerProgressX = FirstFinger.DeltaProgress.x * FirstFinger.DirectionCtrl.x * FirstFinger.Sensitivity.x
                    ObjectEvent.Progress = ObjectEvent.Progress + firstFingerProgressX
                    local progress = limiteProgress(ObjectEvent.Progress)
                    objRotateWithFinger(ObjectEvent, progress)
                end
            end
        end
    end
end

--============================================================
function onSize(w, h)
    if w ~= DeviceInfo.Width or h ~= DeviceInfo.Height then
        DeviceInfo.Width = w
        DeviceInfo.Height = h
    end
end
--============================================================--============================================================
function onDestroy()
    NextAngle:delete()
end